<script lang="ts" setup>
import { getCourseInformationById, getFolderInfoApi, getSourceFileUrlApi, getVideoDetailApi } from '@/api/study/course';
import { useFileTransStore } from '@/stores/fileTransStore';
import { onMounted, ref, watch } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import VideoPlayerComponent from './components/VideoPlayerComponent.vue';
import { getUserMeta } from '@/api/PersonalSpace/PersonalInfo';
import type { CourseFile, SourceFile } from '@/types/course/course';
import NormalHeader from '@/components/NormalHeader.vue';
import PDFShowComponent from './components/PDFShowComponent.vue';

import {
  ArrowLeftOutlined,
  FileTextOutlined,
  LinkOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons-vue';
import type { CustomItemType } from '@/types/NormalMenu/menu';
import router from '@/router';
const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
  folderId: {
    type: String,
    required: true,
  },
  sourceId: {
    type: String,
    required: true,
  },
  filePath: {
    type: String,
    required: true,
  },
});
const route = useRoute();
const folderInfo = ref<CourseFile | null>(null);
const courseName = ref<string>('');
const sourceTag = ref<string | undefined>('');

const fileTransStore = useFileTransStore();
// transResponse的值非常复杂,且在多个组件使用，使用pinia进行存储
const videoSourceFileInfo = async (sourceId: string) => {
  const transResponse = await getVideoDetailApi(sourceId);

  fileTransStore.setData(transResponse);
}

// TODO: 获取文件类型，根据文件类型进行不同的处理，视频则渲染视频组件，文档则渲染文档组件
const getSourceTag = () => {
  if (folderInfo.value) {
    const files = folderInfo.value.childFiles;
    if (!files)
      return undefined;

    const sourceFile = files.flatMap(chapter => chapter.childFiles.flatMap(section => section.sourceFiles)).find(source => source.sourceId === props.sourceId);
    return sourceFile?.tag;
  }
  return undefined;
}

const setSourceTag = () => {
  sourceTag.value = getSourceTag();

  // eslint-disable-next-line no-console
  console.log(sourceTag.value);
}

watch(
  [() => route.params, () => sourceTag.value],
  ([newParams, newSourceTag]) => {
    if (newSourceTag === '音视频')
      videoSourceFileInfo(newParams.sourceId as string);
  },
  { immediate: true },
);

// 获取该课程的层级目录关系
// 获取课程目录信息
const fetchFolderInfo = async () => {
  try {
    const response = await getFolderInfoApi(props.folderId);
    folderInfo.value = response;
  }
  catch (error) {
    message.error("获取课程目录信息失败")
  }
}

// 获取课程标题名称
const fetchCourseName = async () => {
  try {
    const response = await getCourseInformationById(props.courseId);
    courseName.value = response.courseName;
  }
  catch (error) {
    message.error("获取课程元信息失败")
  }
};

// Helper to get icons based on tag
const getIcon = (tag: string) => {
  switch (tag) {
    case '文档':
      return FileTextOutlined;
    case '音视频':
      return VideoCameraOutlined;
    case '资源':
      return FileTextOutlined;
    case '网页资源':
      return LinkOutlined;
    default:
      return null;
  }
};

const getUrl = async (resource: SourceFile | CourseFile) => {
  if (resource.tag === '网页资源') {
    const sourceId = 'sourceId' in resource ? resource.sourceId : resource.courseFileId;
    if (!sourceId) {
      console.error('未提供 sourceId');
      message.error('未提供 sourceId');
      return;
    }

    try {
      const response = await getSourceFileUrlApi(sourceId);
      const fileUrl = response;
      if (fileUrl) {
        return fileUrl;
      }
      else {
        console.error('获取文件URL失败');
        message.error('获取文件URL失败');
      }
    }
    catch (error) {
      console.error('请求失败:', error);
      message.error('请求失败');
    }
  }
  else if (resource.tag === '音视频' || resource.tag === '文档') {
    const sourcePath = 'sourcePath' in resource ? resource.sourcePath : ('filePath' in resource ? resource.filePath : undefined);
    // 需要将sourcePath进行URL编码处理之后再拼接
    if (sourcePath)
      return `/learning/details/${props.courseId}/${props.folderId}/${resource.sourceId}/${encodeURIComponent(sourcePath)}`;
  }

  return undefined;
};

// 生成符合menuList的数据结构
const generateMenuList = async (folderInfo: CourseFile | null) => {
  const files = folderInfo?.childFiles;
  if (!files)
    return undefined;

  const res: CustomItemType[] = await Promise.all(files.map(async chapter => ({
    label: chapter.name || '无名称',
    key: chapter.courseFileId,
    icon: getIcon(chapter.tag ? chapter.tag : ''),
    children: await Promise.all(chapter.childFiles.map(async section => ({
      label: section.name || '无名称',
      key: section.courseFileId,
      icon: getIcon(section.tag ? section.tag : ''),
      children: await Promise.all(section.sourceFiles.map(async resource => ({
        label: resource.name || '无名称',
        key: resource.courseFileId || resource.sourceId || '',
        icon: getIcon(resource.tag),
        url: await getUrl(resource), // 确保这里是字符串
      }))),
    }))),
  })));

  return res
};

// 检查基本信息是否完整
const validateUserMeta = async () => {
  const response = await getUserMeta()

  // 认为以下字段只有有一个空余就是未填写
  if (!response || !response.campus || response.campus === '' || !response.college || response.college === '' || !response.enrollmentYear || response.enrollmentYear === '' || !response.major || response.major === '' || !response.studentId || response.studentId === '' || !response.studentStatus || response.studentStatus === '') {
    Modal.error({
      title: '请前往个人中心完成基本信息的填写',
      content: '观看视频前请保证基本信息完整,不然无法记录学习进度',
    })
  }
}

// 监听 folderInfo 的变化，生成 menuList
const folderList = ref<CustomItemType[]>([]);

watch(folderInfo, async (newFolderInfo) => {
  setSourceTag();
  if (newFolderInfo)
    folderList.value = await generateMenuList(newFolderInfo) || [];
}, { immediate: true });

onMounted(async () => {
  validateUserMeta()
  await fetchFolderInfo()
  fetchCourseName()
  setSourceTag()
})

// 监听路由变化，更新资源类型
watch(() => route.params.filePath, () => {
  validateUserMeta()
  fetchFolderInfo()
  fetchCourseName()
  setSourceTag()
}, { immediate: true });

const goBack = () => {
  router.replace(`/learning/xiangqing/${props.courseId}/${props.folderId}`);
}
</script>

<template>
  <a-layout class="app-layout">
    <NormalHeader title="资源" :menu-title="courseName" :menu-list="folderList" />
    <a-layout-content class="layout-content">
      <!-- 提供返回上一页按钮 -->
      <a-row>
        <a-col :span="24">
          <div style="margin: 0.5rem;" @click="goBack">
            <ArrowLeftOutlined class="icon" />
            <span style="font-size: 1rem;">返回</span>
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col>
          <!-- 标题部分 -->
          <div class="header">
            <h2 class="course-title">
              {{ courseName }}
            </h2>
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <!-- 根据tag进行渲染 -->
          <div v-if="sourceTag === '文档'">
            <PDFShowComponent :source-id="sourceId" />
          </div>
          <div v-else-if="sourceTag === '音视频'">
            <VideoPlayerComponent :source-id="sourceId" :course-id="courseId" />
          </div>
          <div v-else>
            <p>加载中...</p>
          </div>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<style scoped lang="scss">
.app-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.icon {
    font-size: 1rem;
    margin-right: 8px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 20px;
}

.header {
  text-align: center;
  margin-bottom: 1rem;
  width: 100vw;

  .course-title {
    // 居中对齐
    text-align: center;
    font-size: 1.5rem;
    color: #333333;
    margin: 0;
  }
}

.layout-content {
  background-color: #fff;
  padding: 1rem;
  flex: 1;
  overflow-y: auto;
  width: 100%; /* 确保宽度为100% */
}

.learningPage-content {
  width: 100%;
  max-width: 100%; /* 防止内容超出 */
}

.copilot {
  padding: 1rem;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .layout-content {
    padding: 0.5rem;
  }

  .copilot {
    padding: 0.5rem;
  }

  .header {
    .course-title {
      font-size: 1.2rem;
    }
  }
}
</style>
